import {SqliteDatabase} from "tauri-plugin-sqlite-api";
import {invoke} from "@tauri-apps/api/core";

const notebookSql = `CREATE TABLE IF NOT EXISTS notebook (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    directory TEXT NOT NULL,
    createTime TEXT NOT NULL,
    collect INTEGER NOT NULL
)`

const billSql = `CREATE TABLE IF NOT EXISTS bill (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    label TEXT NOT NULL,
    datetime TEXT NOT NULL,
    money REAL NOT NULL,
    small TEXT NOT NULL,
    destination TEXT,
    remark TEXT
)`

export interface NotebookInterface {
    id?: number,
    title: string,
    directory: string,
    createTime: string,
    collect: number
}

export interface BillInterface {
    id?: number,
    label: string,
    datetime: string,
    money: number | string,
    small: string,
    destination: string | null,
    remark: string,
}

export class LeiToolsNotebookDatabase extends SqliteDatabase{
    constructor(path: string) {
        super(path, 'notebook');
    }
    public async createTable(): Promise<number> {
        return await this.execute(notebookSql)
    }
}


export class LeiToolsBillDatabase extends SqliteDatabase{
    constructor(path: string) {
        super(path, 'bill');
    }
    public async createTable(): Promise<number> {
        return await this.execute(billSql)
    }
}

export async function read_file(path: string): Promise<string> {
    return await invoke('read_file', {path})
}

export async function write_file(path: string, content: string): Promise<void> {
    await invoke('write_file', {path, content})
}

export async function delete_file(path: string): Promise<void> {
    await invoke('delete_file', {path})
}

export function isSameWeek(timeStampA: number, timeStampB: number): boolean {
    const dateA = new Date(timeStampA);
    const dateB = new Date(timeStampB);

    // 获取当天凌晨的时间戳（毫秒）
    const dayA = dateA.setHours(0, 0, 0, 0);
    const dayB = dateB.setHours(0, 0, 0, 0);

    // 计算总天数（1970-01-01 是周四）
    const oneDay = 1000 * 60 * 60 * 24;
    const totalDaysA = Math.floor(dayA / oneDay);
    const totalDaysB = Math.floor(dayB / oneDay);

    // 通过 (总天数 + 4) / 7 取整计算周数（以周一为每周第一天）
    return Math.floor((totalDaysA + 4) / 7) === Math.floor((totalDaysB + 4) / 7);
}

export async function queryTable(table: string): Promise<boolean> {
    const db = new SqliteDatabase('./sqlite.db', 'sqlite_master')
    await db.open()
    const res = await db.query(`name='${table}'`)
    await db.close()
    return res.length > 0
}
